<?php
/**
 * 根据wechat_user_error表再次获取微信用户信息并插入wechat_userinfo_new表
 * @author panchenxing@star-net.cn
 * @copyright  ktvme. All Rights Reserved.
 * @version $Id: Email.php 3 2017-05-08 03:02:47Z chendanming $
 */

namespace app\console\swooletask\logic;


use app\wechat\model\WechatUserError;
use think\Log;
use app\wechat\service\Wechat;
use app\wechat\model\WechatUserInfoNew;

class WechatUserInfoAgain {

    /**
     * 再次获取微信用户信息并插入wechat_userinfo_new表，插入成功则从error表中删除
     * @param $wechat
     * @return array
     */
    public function wechatUserInfoAgain($wechat) {
        //        Log::record(['more_info' => ['swoole_server_onreceive'=>json_encode($wechat)]], 'elk');
        //        Log::save();
        $list          = $wechat['list'];
        $userID        = $list['UserID'];
        $wechatService = new Wechat();
        $ret           = $wechatService->getUserInfoOne($list['OpenID']);
        if(!$ret || $ret['errcode']) {
            Log::record(json_encode(['get_userinfo_error_again_data' => $list]), 'elk_more_info','wechat_userinfo_again');
            Log::record(json_encode(['get_userinfo_error_again' => $ret]), 'elk_more_info','wechat_userinfo_again');
            //Log::save();
            return $ret;
        }
        if($ret['subscribe'] == 0) return $ret;  //未关注
        $userInfo = [
            'UserID'        => $userID,
            'Sex'           => $ret['sex'],
            'City'          => $ret['city'],
            'Province'      => $ret['province'],
            'Country'       => $ret['country'],
            'Language'      => $ret['language'],
            'HeadImgURL'    => $ret['headimgurl'],
            'SubscribeTime' => $ret['subscribe_time'],
            'OpenID'        => $ret['openid'],
            'TagidList'     => json_encode($ret['tagid_list']),
        ];
        //微信昵称特殊昵称过滤处理
        $match = array();
        preg_match_all('/[\x{4e00}-\x{9fa5}A-Za-z0-9_]+/u', $ret['nickname'], $match);
        $wxNickname          = implode("", $match[0]);
        $userInfo['Nickame'] = ($wxNickname != '' and mb_strlen($wxNickname, "UTF8") < 40) ? $wxNickname : '';
        //插入userinfonew表
        $wechatUserInfoNewModel = new WechatUserInfoNew();
        $result                 = $wechatUserInfoNewModel->insert($userInfo);
        if(!$result) {
            Log::record(json_encode(['insert_wechat_userinfo_error' => $result]), 'elk_more_info','wechat_userinfo_again');
            Log::record(json_encode(['insert_wechat_userinfo_data' => $userInfo]), 'elk_more_info','wechat_userinfo_again');
            //Log::save();

            return $result;
        }

        //插入成功,删除wechar_user_error表中的相关数据
        $wechatUserErrorModel = new WechatUserError();
        return $wechatUserErrorModel->where('UserID',$userID)->delete();
    }
}